//
//  MusicCustomModeViewController.swift
//  NDAi
//
//  Created by 丸子 on 2024/7/25.
//

import UIKit
import JXSegmentedView
import IQKeyboardManagerSwift
class MusicCustomModeViewController: UIViewController, JXSegmentedListContainerViewListDelegate {
    var isOpen:Bool = false {
        didSet {
            self.tableView.reloadData()
        }
    }
    let disposeBag = DisposeBag()
    var viewModel = MusicCustomViewModel()
    private lazy var tableView: UITableView = {
        let view = UITableView(frame: .zero, style: .grouped)
        view.backgroundColor = .clear
        view.delegate = self
        view.dataSource = self
        view.register(cellWithClass: MusicLyricStyleCell.self)
        view.register(cellWithClass: MusicStyleCell.self)
        view.register(cellWithClass: MusicTitleStyleCell.self)
        view.rowHeight = UITableView.automaticDimension
        view.sectionHeaderHeight = 0
        view.estimatedSectionHeaderHeight = 0
        view.sectionFooterHeight = 0
        view.estimatedSectionFooterHeight = 0
        view.contentInsetAdjustmentBehavior = .never
        view.separatorStyle = .none
        return view
    }()
    
    private lazy var saveBtn: UIButton = {
        let button = UIButton(type: .custom)
        button.titleForNormal = "创作音乐"
        button.titleFont = UIFont.pingFangSCRegular(ofSize: 16)
        button.backgroundColor = UIColor(hexString: "#25262B")
        button.allRound(24)
        return button
    }()
    override func viewWillAppear(_ animated: Bool) {
        super.viewWillAppear(animated)
        IQKeyboardManager.shared.enable = true

        IQKeyboardManager.shared.shouldResignOnTouchOutside = true
    }
    override func viewWillDisappear(_ animated: Bool) {
        super.viewWillDisappear(animated)
        IQKeyboardManager.shared.enable = false
    }
    override func viewDidLoad() {
        super.viewDidLoad()
       
        self.view.addSubview(tableView)
        self.view.addSubview(saveBtn)
        self.tableView.snp.makeConstraints { make in
            make.top.equalTo(self.safeTop)
            make.leading.trailing.equalToSuperview()
            make.bottom.equalTo(self.saveBtn.snp.top).offset(0)
        }
        
        saveBtn.snp.makeConstraints { make in
            make.bottom.equalTo(self.safeBottom).offset(-8)
            make.leading.trailing.equalToSuperview().inset(16)
            make.height.equalTo(48)
        }
        
        saveBtn.setClosureTouchUpInside_k { [weak self] in
            guard let self = self else { return }
            self.showBuyVideo()
        }
        viewModel.getStyleList()
        viewModel.reloadListSubject.subscribe(onNext: { [weak self] in
            self?.tableView.reloadData()
        }).disposed(by: disposeBag)
        
        viewModel.createSuccessSubject.subscribe(onNext: {[weak self] checkId in
            let vc = MusicGenerateViewController()
            vc.checkId = checkId
            self?.navigationController?.pushViewController(vc)
        }).disposed(by: disposeBag)
    }
    
    func listView() -> UIView {
        return view
    }
    var lose:Int = 0
   
    
    func showBuyVideo(){
        if !Appearance.shared.isLoign {
            GlobalRx.loginSubject.onNext(())
            return
        }
        if !self.viewModel.is_instrumental {
            guard let desc = self.viewModel.music_lyric else {
                NDProgressHUD.show(message: "请输入歌词")
                return
            }
        }
        guard let musicName = self.viewModel.music_name, !musicName.isEmpty else {
            NDProgressHUD.show(message: "请输入标题")
            return
        }
        if let score = Appearance.shared.accoutModel?.userOtherInfo?.score {
            if score < Int(self.lose) {
                self.nomoreScore(score: score)
            }else {
                self.generatePOPView(score: score)
            }
        }
    }
    
    func nomoreScore(score:Int){
        let user = Appearance.shared.accoutModel
        if user?.userOtherInfo?.is_vip == 1 {
            let view = VideoTopupView()
            Appearance.addViewToWindow(view)
            view.chooseDone = { [weak self] in
                let vc = DiamondBuyViewController()
                self?.navigationController?.pushViewController(vc)
            }
        }else {
            let view = VideoTopupView()
            view.titleLabel.text = "钻石余额不足, 升级会员可获增钻石"
            view.confirmButton.titleForNormal = "立即升级"
            Appearance.addViewToWindow(view)
            view.chooseDone = { [weak self] in
                let vc = SubscribeViewController()
                self?.navigationController?.pushViewController(vc)
            }
        }
    }
    
    func generatePOPView(score:Int){
        let view = VideoBuyView()
        Appearance.addViewToWindow(view)
        view.initViews(money: "\(score)", lose: "\(self.lose)", title: "生成音乐将花费\(self.lose)钻石")
        view.chooseDone = { [weak self] in
            self?.viewModel.musicCreate()
        }
    }
    
}
extension MusicCustomModeViewController: UITableViewDelegate, UITableViewDataSource, UIScrollViewDelegate {
    func numberOfSections(in tableView: UITableView) -> Int {
        return 3
    }
    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return 1
    }
    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        if indexPath.section == 0 {
            let cell = tableView.dequeueReusableCell(withClass: MusicLyricStyleCell.self)
            cell.switchBtn.setClosureTouchUpInside_k { [weak self] in
                guard let self = self else { return }
                self.isOpen = !self.isOpen
                cell.switchBtn.isSelected = self.isOpen
                
                cell.descView.isHidden = self.isOpen
                cell.descTextView.isHidden = self.isOpen
                cell.countLb.isHidden = self.isOpen
                cell.buttonBtn.isHidden = self.isOpen
                self.viewModel.is_instrumental = self.isOpen
            }
            cell.descTextView.text = self.viewModel.music_lyric
            cell.chooseDesc = {[weak self] lyric in
                guard let self = self else { return }
                self.viewModel.music_lyric = lyric
            }
            cell.buttonBtn.setClosureTouchUpInside_k { [weak self] in
                guard let self = self else { return }
                self.viewModel.generateLyric()
            }
            return cell
        }else if indexPath.section == 1 {
            let cell = tableView.dequeueReusableCell(withClass: MusicStyleCell.self)
            cell.descTextView.text = self.viewModel.style_text
            cell.setstylelist(list: self.viewModel.stlyeList)
            cell.chooseDesc = {[weak self] style in
                guard let self = self else { return }
                self.viewModel.style_text = style
            }
            cell.buttonBtn.setClosureTouchUpInside_k { [weak self] in
                guard let self = self else { return }
                self.viewModel.RandomStyle()
            }
            cell.chooseStyle = { [weak self] style in
                guard let self = self else { return }
                self.viewModel.appendStyle(style)
            }
            return cell
        }else {
            let cell = tableView.dequeueReusableCell(withClass: MusicTitleStyleCell.self)
            cell.inputFiled.text = self.viewModel.music_name
            cell.chooseTitlte = {[weak self] title in
                guard let self = self else { return }
                self.viewModel.music_name = title
            }
            return cell
        }
    }
    func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
        if indexPath.section == 0 {
            //34
            return isOpen ? 56 : 192
        }else if indexPath.section == 1 {
            return 284
        }else {
            return 92
        }
    }
    func tableView(_ tableView: UITableView, viewForFooterInSection section: Int) -> UIView? {
        return UIView()
    }
    func tableView(_ tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? {
        return UIView()
    }
    func tableView(_ tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat {
        return 0.01
    }
    func tableView(_ tableView: UITableView, heightForFooterInSection section: Int) -> CGFloat {
        return 0.01
    }
    
   
}
